;;; guile-openai --- An OpenAI API client for Guile
;;; Copyright © 2023 Andrew Whatson <whatson@tailcall.au>
;;;
;;; This file is part of guile-openai.
;;;
;;; guile-openai is free software: you can redistribute it and/or modify
;;; it under the terms of the GNU Affero General Public License as
;;; published by the Free Software Foundation, either version 3 of the
;;; License, or (at your option) any later version.
;;;
;;; guile-openai is distributed in the hope that it will be useful, but
;;; WITHOUT ANY WARRANTY; without even the implied warranty of
;;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
;;; Affero General Public License for more details.
;;;
;;; You should have received a copy of the GNU Affero General Public
;;; License along with guile-openai.  If not, see
;;; <https://www.gnu.org/licenses/>.

(define-module (openai api model)
  #:use-module (openai client)
  #:use-module (json record)
  #:export (make-model
            json->model
            model->json
            model?
            model-id
            model-created
            model-owned-by
            model-permissions
            model-parent
            model-root

            make-model-permission
            json->model-permission
            model-permission->json
            model-permission?
            model-permission-id
            model-permission-created
            model-permission-create-engine?
            model-permission-sampling?
            model-permission-logprobs?
            model-permission-search-indices?
            model-permission-view?
            model-permission-fine-tuning?
            model-permission-organization
            model-permission-group
            model-permission-blocking?

            fetch-all-models
            fetch-model))

(define-json-type <model-list>
  (object)
  (data "data" #(<model>)))

(define-json-type <model>
  (id)
  (object)
  (created)
  (owned-by    "owned_by")
  (permissions "permission" #(<model-permission>))
  (parent)
  (root))

(define-json-type <model-permission>
  (id)
  (object)
  (created)
  (create-engine?  "allow_create_engine")
  (sampling?       "allow_sampling")
  (logprobs?       "allow_logprobs")
  (search-indices? "allow_search_indices")
  (view?           "allow_view")
  (fine-tuning?    "allow_fine_tuning")
  (organization)
  (group)
  (blocking?       "is_blocking"))

(define (fetch-all-models)
  (model-list-data
   (json->model-list
    (openai-get "/v1/models"))))

(define (fetch-model name)
  (json->model
   (openai-get (list "/v1/models/"
                     (if (symbol? name)
                         (symbol->string name)
                         name)))))
